﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.UI;
using Camc.Quality.Bop;
using Camc.Quality.Bop.Dto;
using Camc.Quality.Bop.TreeObject;
using Camc.Quality.Dto.ProcessesEntityDto;
using Camc.Quality.Dto.TableDto.BopDto.Substance;
using Camc.Quality.Dto.TableOutDto;
using Camc.Quality.Quality;
using Camc.Quality.RecordTable.FormClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Abp.Linq.Extensions;
using Microsoft.EntityFrameworkCore;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Materials;
using System.Reflection;
using System.ComponentModel;
using Camc.Quality.BomMake.Dto;
using Camc.Quality.DataDictionary;
using Abp.Domain.Uow;
using Camc.Quality.Common;
using Camc.Quality.IOperationHistory;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.StoreManagement;

namespace Camc.Quality.BomMake
{
    /// <summary>
    /// 制造bom
    /// </summary>
    public class BomMakeContentAppService : QualityAppServiceBase
    {
        public List<TreeClass> treeNodes = new List<TreeClass>();
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<BopContent, Guid> _bopContentRepository;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        private readonly IRepository<BomMakeContent, Guid> _bomMakeContentRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        private readonly StoreFunctionsAppService _storeFunctionsAppService;
        public BomMakeContentAppService(
           IRepository<MakeTask, Guid> makeTaskRepository,
           IRepository<BopNode, Guid> bopNodeRepository,
           IRepository<BopDesc, Guid> bopDescRepository,
           IRepository<BopContent, Guid> bopContentRepository,
           IRepository<ProcessesEntity, Guid> processesEntityRepository,
           IRepository<WorkStepEntity, Guid> workStepEntityRepository, IRepository<LoadPieceEntity, Guid> loadPieceRepository, IRepository<User, long> userRepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<TechniqueEntity, Guid> techniqueEntityRepository, IRepository<BomMakeContent, Guid> bomMakeContentRepository, IRepository<Sys_Code, Guid> sysCodeRepository, IRepository<MaterialsNode, Guid> materialsNodeRepository, IUnitOfWorkManager unitOfWorkManager, IOperationHistoryAppService iOperationHistoryAppService, StoreFunctionsAppService storeFunctionsAppService)
        {
            this._bopNodeRepository = bopNodeRepository;
            this._bopDescRepository = bopDescRepository;
            this._bopContentRepository = bopContentRepository;
            this._processesEntityRepository = processesEntityRepository;
            this._workStepEntityRepository = workStepEntityRepository;
            this._loadPieceRepository = loadPieceRepository;
            this._userRepository = userRepository;
            this._bomDesignDetailrepository = bomDesignDetailrepository;
            this._bomDesignrepository = bomDesignrepository;
            this._materialsContentRepository = materialsContentRepository;
            this._techniqueEntityRepository = techniqueEntityRepository;
            this._bomMakeContentRepository = bomMakeContentRepository;
            this._sysCodeRepository = sysCodeRepository;
            this._materialsNodeRepository = materialsNodeRepository;
            this._unitOfWorkManager = unitOfWorkManager;
            this._iOperationHistoryAppService = iOperationHistoryAppService;
            _makeTaskRepository = makeTaskRepository;
            this._storeFunctionsAppService = storeFunctionsAppService;
        }
        /// <summary>
        /// Bom查看
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public BomMakeTreeGridDto GetBopTreeGrid(Guid guid, Guid loatId)
        {
            //根据发次id 获取芯级
            BomMakeTreeGridDto output = new BomMakeTreeGridDto();
            var bopDescTemp = _bopDescRepository.GetAll().Where(d => d.ModelId == guid && d.LotNoId == loatId).FirstOrDefault();
            if (bopDescTemp != null)
            {
                output.data.Id = bopDescTemp.Id;
                output.data.ParentId = Guid.Empty;
                output.data.MaterialNo = bopDescTemp.DrawingNo;
                output.data.MaterialName = bopDescTemp.ModelName;
                output.data.Module = bopDescTemp.Model;
                output.data.SendTime = bopDescTemp.LotNo;
                output.data.IsRelation = 0;
                output.data.LevelRelationship = "1";
                output.data.NodeLevel = 0;
                output.data.LevelNum = 1;
                int i = 0;
                List<BomMakeDetaillist> bomMakeDetaillists = new List<BomMakeDetaillist>();
                LoadChildNode(bopDescTemp.Id, output.data.LevelNum, new BomMakeDetaillist(), bomMakeDetaillists);
                output.children = bomMakeDetaillists;
                return output;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 加载bop节点递归
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="treeNodeDto"></param>

        private void LoadChildNode(Guid Id, int level, BomMakeDetaillist treeNodeDto, List<BomMakeDetaillist> bomMakeDetaillists)
        {
            var bopNodeList = _bopNodeRepository.GetAll().Where(c => c.ParentId == Id).OrderBy(d => d.CreationTime).ToList(); //add 12/2
            //var list = ObjectMapper.Map<List<BopNodeDto>>(bopNodeList);
            for (int i = 0; i < bopNodeList.Count(); i++)
            {
                BomMakeDetaillist temp1 = new BomMakeDetaillist();
                temp1.data.Id = bopNodeList[i].Id;
                temp1.data.NodeName = bopNodeList[i].NodeName;
                temp1.data.NodeDrawingNo = bopNodeList[i].NodeDrawingNo;
                //temp1.data.IsRelation = bopNodeList[i].IsRelation;
                temp1.data.ParentId = bopNodeList[i].ParentId;
                temp1.data.NodeLevel = bopNodeList[i].NodeLevel;
                //temp1.data.LevelName = bopNodeList[i].LevelName;
                //temp1.data.MaterialLevel = bopNodeList[i].MaterialLevel;
                temp1.data.ParentCode = bopNodeList[i].ParentCode;
                temp1.data.NodeCode = bopNodeList[i].NodeCode;
                temp1.data.IsLeaf = bopNodeList[i].IsLeaf;
                temp1.data.IsExport = bopNodeList[i].IsExport;
                //temp1.data.AssortStatusDesc = bopNodeList[i].AssortStatusDesc;
                //temp1.data.OutboundStatusDesc = bopNodeList[i].OutboundStatusDesc;
                //temp1.data.Name = bopNodeList[i].Name;
                //temp1.data.Number = bopNodeList[i].Number;
                //temp1.data.Remark = bopNodeList[i].Remark;
                //temp1.data.Code = bopNodeList[i].Code;
                //temp1.data.MaterialProperty = bopNodeList[i].MaterialProperty;
                temp1.data.MaterialName = bopNodeList[i].NodeName;
                temp1.data.MaterialNo = bopNodeList[i].NodeDrawingNo;
                //temp1.data.MaterialTypeCode = bopNodeList[i].MaterialTypeCode;
                //temp1.data.MaterialsNodeId = bopNodeList[i].MaterialsNodeId;
                //temp1.data.MaterialsTypeName = bopNodeList[i].MaterialsTypeName;
                //temp1.data.MaterialCategoryName = bopNodeList[i].MaterialCategoryName;
                //temp1.data.UnitId = bopNodeList[i].UnitId;
                //temp1.data.Unit = bopNodeList[i].Unit;
                //temp1.data.Module = bopNodeList[i].Module;
                //temp1.data.Unit1BomDosage = bopNodeList[i].Unit1BomDosage;
                //temp1.data.SuiteStock = bopNodeList[i].SuiteStock;
                //temp1.data.UsableQuantityStock = bopNodeList[i].UsableQuantityStock;
                //temp1.data.StarvingStock = bopNodeList[i].StarvingStock;
                //temp1.data.DeliveryStockAll = bopNodeList[i].DeliveryStockAll;
                //temp1.data.PreSuiteName = bopNodeList[i].PreSuiteName;
                //temp1.data.PreSuiteTime = bopNodeList[i].PreSuiteTime;
                //temp1.data.CompletePeople = bopNodeList[i].CompletePeople;
                //temp1.data.CompleteTime = bopNodeList[i].CompleteTime;
                temp1.data.LevelNum = bopNodeList[i].NodeLevel + 1;
                //temp1.data.ModuleHJ =
                //temp1.data.SendTime =
                //temp1.data.XjName=
                //temp1.data.BTName=
                //temp1.data.GCName =
                List<BomMakeDetaillist> childrenlist = new List<BomMakeDetaillist>();
                LoadChildNode(bopNodeList[i].Id, bopNodeList[i].NodeLevel, temp1, childrenlist);
                if (bopNodeList[i].TechniqueEntityId == null)
                {
                    temp1.data.LevelNum = bopNodeList[i].NodeLevel + 1;
                    temp1.data.IsRelation = 0;
                    temp1.children = childrenlist;
                }
                else
                {
                    List<BomMakeDetaillist> treeBomMakeDetaillist = new List<BomMakeDetaillist>();
                    temp1.data.IsRelation = 1;
                    LoadTechquine(bopNodeList[i].Id, temp1.data.LevelNum, treeBomMakeDetaillist);
                    var tech = _techniqueEntityRepository.Get(bopNodeList[i].TechniqueEntityId.Value);
                    temp1.data.OutboundStatusDesc = GetEnumDesc(tech.OutboundState);
                    temp1.children = treeBomMakeDetaillist;
                }
                bomMakeDetaillists.Add(temp1);
                // bomMakeTreeGridDto.children.Add(tree);
                //递归性质，函数内调用自身函数
                //NodeLevel++;


                //GetProductionTechquine(item.Id, tree);
                //NodeLevel--;
                //递归结束的终点条件
                //  
            }
        }


        /// <summary>
        /// 懒加载获取工序工步树节点
        /// </summary>
        /// <param name="NodeId"></param>
        /// <returns></returns>
        private void GetProductionTechquine(Guid NodeId, AssignmentTreeOutput assignmentTreeOutput)
        {
            // AssignmentTreeOutput output = new AssignmentTreeOutput();
            // LoadTechquine(NodeId, assignmentTreeOutput);
            // return output.TreeList;
        }
        /// <summary>
        /// 加载工步工序节点
        /// </summary>
        /// <param name="NodeId"></param>
        /// <param name="treeNodeDto"></param>
        private void LoadTechquine(Guid NodeId, int LevelString, List<BomMakeDetaillist> bomMakeDetaillist)
        {

            //获取节点信息的工艺规程编码
            var bomNode = _bopNodeRepository.FirstOrDefault(x => x.Id == NodeId);
            string processCode = bomNode.ProcessCode;
            //根据工艺规程编码获取工艺文件表Id,已关联文件
            var tech = _techniqueEntityRepository.FirstOrDefault(x => x.Id == bomNode.TechniqueEntityId);
            if (tech == null) return;
            Guid techId = tech.Id;
            //获取工序和工步的信息，并做相应的排序
            var processesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == techId).OrderBy(n => n.ProcessesSequence).ToList();
            processesList.ToList().ForEach(q => q.WorkStepEntities = q.WorkStepEntities.OrderBy(r => r.WorkStepNumber).ToList());
            //循环遍历，往Node里面赋值
            for (int i = 0; i < processesList.ToList().Count; i++)
            {
                int index = i + 1;
                BomMakeDetaillist tree = new BomMakeDetaillist();
                tree.data.Id = processesList[i].Id;
                tree.data.ParentId = NodeId;
                tree.data.MaterialNo = "工序" + processesList[i].ProcessesSequence.ToString() + " ";
                tree.data.MaterialName = processesList[i].ProcessesName;
                tree.data.IsRelation = 0;
                tree.data.NodeLevel = 8;
                tree.data.OutboundStatusDesc = GetEnumDesc(processesList[i].OutboundState);
                tree.data.LevelNum = 4;
                //查询工步
                List<WorkStepEntity> workStepEntities = processesList[i].WorkStepEntities.ToList();
                for (int k = 0; k < workStepEntities.Count; k++)
                {
                    int indexTwo = k + 1;
                    BomMakeDetaillist wtree = new BomMakeDetaillist();
                    wtree.data.Id = workStepEntities[k].Id;
                    wtree.data.ParentId = processesList[i].Id;
                    wtree.data.MaterialNo = "工步" + workStepEntities[k].WorkStepNumber.ToString();// + "-"+ witem.WorkStepNumber.ToString();
                    wtree.data.MaterialName = workStepEntities[k].WorkStepNumber.ToString();//witem.WorkStepName  这个值数据库有问题
                    wtree.data.IsRelation = 0;
                    wtree.data.NodeLevel = 9;
                    wtree.data.OutboundStatusDesc = GetEnumDesc(workStepEntities[k].OutboundState);
                    wtree.data.LevelRelationship = indexTwo.ToString();
                    wtree.data.LevelNum = 5;
                    var InsertDetailsEntitys = (from loadPieceData in _loadPieceRepository.GetAll().Where(p => p.WorkStepEntityId == workStepEntities[k].Id).OrderBy(n => n.Sort)
                                                join materilasData in _materialsContentRepository.GetAll() on loadPieceData.MaterialsContentId equals materilasData.Id
                                                join queryNode in _materialsNodeRepository.GetAll() on materilasData.MaterialsNodeId equals queryNode.Id
                                                join queryNodeChild in _materialsNodeRepository.GetAll() on materilasData.MaterialCategoryId equals queryNodeChild.Id
                                                join code in _sysCodeRepository.GetAll() on materilasData.UnitId equals code.Id
                                                 into codeData
                                                from cd in codeData.DefaultIfEmpty()
                                                select new BomMakeEditChildData
                                                {
                                                    Id = loadPieceData.Id,
                                                    Name = loadPieceData.Name,
                                                    Code = loadPieceData.Code,
                                                    MaterialNo = materilasData.MaterialNo,
                                                    Module = materilasData.Model,
                                                    Unit = cd.Description,
                                                    Number = loadPieceData.Number,
                                                    Remark = loadPieceData.Remark,
                                                    MaterialsTypeName = queryNode.MaterialTypeName,
                                                    MaterialCategoryName = queryNodeChild.MaterialTypeName,
                                                    MaterialProperty = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materilasData.MaterialProperty.ToString()).ToString()
                                                }).ToList();
                    //var joinBomInsertDetailsEntitys =from  queryData in InsertDetailsEntitys 
                    //                                 join queryBomData in _bomDesignDetailrepository.GetAll()
                    //                                 on queryData.MaterialsContentId equals 
                    if (InsertDetailsEntitys != null && InsertDetailsEntitys.Count() > 0)
                    {
                        //  var innsertDetailData = ObjectMapper.Map<List<InsertDetailsDto>>(InsertDetailsEntitys.OrderBy(n => n.Index));
                        for (int c = 0; c < InsertDetailsEntitys.Count(); c++)
                        {
                            int indexThree = c + 1;
                            BomMakeDetaillist ltree = new BomMakeDetaillist();
                            ltree.data.Id = InsertDetailsEntitys[c].Id;
                            //名称
                            ltree.data.MaterialName = InsertDetailsEntitys[c].Name;
                            //型号
                            //ltree.data.Code = InsertDetailsEntitys[c].Code;
                            ltree.data.Module = InsertDetailsEntitys[c].Module;
                            //图号
                            ltree.data.MaterialNo = InsertDetailsEntitys[c].MaterialNo;
                            //bom用量
                            ltree.data.Unit1BomDosage = InsertDetailsEntitys[c].Number;
                            //bom层级
                            ltree.data.LevelNum = indexThree;
                            //单位
                            ltree.data.Unit = InsertDetailsEntitys[c].Unit;
                            //备注 
                            ltree.data.Remark = InsertDetailsEntitys[c].Remark;
                            //物料类别
                            ltree.data.MaterialsTypeName = InsertDetailsEntitys[c].MaterialsTypeName;
                            //物料细分类别
                            ltree.data.MaterialCategoryName = InsertDetailsEntitys[c].MaterialCategoryName;
                            //物料属性
                            ltree.data.MaterialProperty = InsertDetailsEntitys[c].MaterialProperty;
                            ltree.data.LevelNum = 6;
                            //处理年代号
                            string yearStr = "";
                            string yearsNoZs = "";
                            string no = "";
                            int length = 0;
                            if (ltree.data.MaterialsTypeName == "标准件")
                            {
                                StandardOutputDto standardOutputDto = _storeFunctionsAppService.GetStandardDrawingNoDispose(InsertDetailsEntitys[c].Code);
                                if (standardOutputDto != null)
                                {
                                    yearsNoZs = standardOutputDto.YearNo;
                                }
                            }
                            ltree.data.YearsNo = yearsNoZs;
                            wtree.children.Add(ltree);
                        }
                    }
                    tree.children.Add(wtree);
                }
                bomMakeDetaillist.Add(tree);
            }
        }

        /// <summary>
        /// 根据枚举获取枚举描述信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static string GetEnumDesc(System.Enum parm)
        {
            FieldInfo enumInfo = parm.GetType().GetField(parm.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] enumAttributes
                = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return parm.ToString();
        }
        private void InitFiledNodeMap(Dictionary<string, FiledNodeMap> filedMap)
        {
            filedMap.Add("装入件明细", new FiledNodeMap(new List<string> { "代号", "名称", "数量", "备注" }, new List<string> { "code", "name", "number", "remark" }));
        }
        /// <summary>
        /// 生产计划型号的模糊查询
        /// </summary>
        /// <param name="model">为空则全库查</param>
        /// <returns></returns>
        public List<string> GetAssignmentModelList(string model)
        {
            var query = _bopDescRepository.GetAll();
            if (string.IsNullOrEmpty(model))
            {
                return query.Select(d => d.Model).Distinct().ToList();
            }
            else
            {
                return query.Where(d => d.Model.Contains(model)).Select(d => d.Model).Distinct().ToList();
            }
        }

        /// <summary>
        /// 发次的模糊查询（基于型号查询数据）必须先选择型号
        /// </summary>
        /// <param name="lotstr"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<string> GetLotNoList(string lotstr, string model)
        {
            var query = _bopDescRepository.GetAll();
            if (!string.IsNullOrEmpty(model))
            {
                query = query.Where(d => d.Model.Contains(model));
                if (!string.IsNullOrEmpty(lotstr))
                {
                    query = query.Where(d => d.LotNo.Contains(lotstr));
                }
                return query.Select(d => d.LotNo).Distinct().ToList();
            }
            else
            {
                throw new UserFriendlyException("请先选择型号！");
            }
        }
        /// <summary>
        /// Bop任务表查询，传参是Fliter过滤，模糊查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMakeContentDto>> GetBopDescList(BomMakePageEditDto input)
        {
            try
            {
                var query = _bopDescRepository.GetAll()
                .WhereIf(!input.Model.IsNullOrWhiteSpace(), x => x.Model.Contains(input.Model)
                ).WhereIf(!input.SendTime.IsNullOrWhiteSpace(), x => x.LotNo.Contains(input.SendTime)
                ).WhereIf(!input.MaterialsNo.IsNullOrWhiteSpace(), x => x.DrawingNo.Contains(input.MaterialsNo));
                var count = await query.CountAsync();
                var bopDescList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                var list = ObjectMapper.Map<List<BomMakeContentDto>>(bopDescList);
                foreach (var item in list)
                {
                    var user = await UserManager.GetUserByIdAsync((long)item.CreatorUserId);
                    item.CreateUserName = user.Surname + user.Name;
                }
                return new PagedResultDto<BomMakeContentDto>(count, list);
            }
            catch (Exception e)
            {
                throw;
            }

        }
        /// <summary>
        /// 同步bom
        /// </summary>
        /// <param name="input"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public async Task<ResultMessage> SynchronizationBom(BomMakeContentDto bomMakeContentDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                List<MaterialsContent> materialsList = new List<MaterialsContent>();
                MaterialsContent materialsContent = new MaterialsContent();
                #region 根据parentId找出相关信息
                //找出根节点下的所有节点信息
                var bopNodeList = from queryBopNodes in _bopNodeRepository.GetAll().Where(c => c.BopDescId == bomMakeContentDto.Id && c.TechniqueEntityId != null)
                                  select queryBopNodes;
                if (bopNodeList == null) 
                {
                    resultMessage.Message = "没有对应规程";
                    resultMessage.code = 1;
                    return resultMessage;
                }
                //找出tech表下的所有工步
                var workStepNodeList = from queryWorkSetpNodes in _workStepEntityRepository.GetAll()
                                       join queryBopNodeList in bopNodeList on queryWorkSetpNodes.TechniqueEntityId equals queryBopNodeList.TechniqueEntityId
                                       select queryWorkSetpNodes;
                //找出所有工步下的装入件明细
                var loadPieceList = from queryLoadPieces in _loadPieceRepository.GetAll()
                                    join queryWorkStepNodes in workStepNodeList on queryLoadPieces.WorkStepEntityId equals queryWorkStepNodes.Id
                                    select queryLoadPieces;
                #endregion
                if (loadPieceList != null && loadPieceList.Count() > 0)
                {
                    #region  根据型号、发次、图号 查询bom的相关物料
                    //var bomDesigMaterialsList = _bomDesignrepository.FirstOrDefaultAsync(t => t.Module == input.Model && t.SendTime == input.LotNo).Result;
                    //if (materialsList == null) 
                    //{
                    //    throw new UserFriendlyException("无对应该发次的bom数据");
                    //}
                    ////根据bomDesign id 获取零件详细信息
                    //var bomMaterialsList = from queryBomMaterials in _bomDesignDetailrepository.GetAll().Where(t => t.BomDesignId == bomDesigMaterialsList.Id && t.LevelNum > 4)
                    //                       join queryMaterialsContent in _materialsContentRepository.GetAll() on queryBomMaterials.MaterialId equals queryMaterialsContent.Id
                    //                       where queryMaterialsContent.MaterialProperty == 3
                    //                       select queryBomMaterials;

                    var materialsContents =
                    from queryMaterialsContent in _materialsContentRepository.GetAll()
                    join queryMaterialsNode in _materialsNodeRepository.GetAll() on queryMaterialsContent.MaterialsNodeId equals queryMaterialsNode.Id
                    where queryMaterialsContent.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件
                    select new
                    {
                        MaterialNo = queryMaterialsContent.MaterialNo,
                        MaterialsNodeName = queryMaterialsNode.MaterialTypeName,
                        Model = queryMaterialsContent.Model,
                        Id = queryMaterialsContent.Id
                    };

                    //if (bomMaterialsList != null && bomMaterialsList.Count() > 0) 
                    //{
                    //找出bop相关装入件物料 分割 图号     图号 ---规格 
                    StringBuilder errorMsg = new StringBuilder();
                    string errorsg = "";
                    var materialsJoin = materialsContents;
                    await loadPieceList.ForEachAsync(t =>
                    {
                        //  string[] module = t.Code.Split('-');
                        //  //针对于标准件标准格式为（图号 空格 型号） 带空格 后期改为 以空格分割  零件标准格式 有可能有型号或者无
                        //  if (module.Length > 1)
                        //  {
                        //      var materialsContentDefault = materialsJoin.FirstOrDefault(c => c.MaterialNo == module[0] && c.Model == module[1]);
                        //      if (materialsContentDefault != null)
                        //      {
                        //          //已存在物料 将物料id 更新到bop明细件id中
                        //          t.MaterialsContentId = materialsContentDefault.Id;
                        //          _loadPieceRepository.UpdateAsync(t);
                        //      }
                        //      else {
                        //          //    //否则提示新增
                        //          //    errorsg += "物料名称：" + t.Name + ",图号：" + module[0] + "," + "规格：" + module[1] + "。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                        //      }
                        //  }
                        ////针对于零件标准格式 有可能有型号或者无
                        //  else
                        //  {


                        //      //if (module.Length > 1)
                        //      //{
                        //      //    //否则提示新增
                        //      //    errorsg += "物料名称：" + t.Name + ",图号：" + module[0] + "," + "规格：" + module[1] + "。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                        //      //}
                        //      //else 
                        //      //{
                        //      //    errorsg += "物料名称：" + t.Name + ",图号：" + module[0] + "," + "规格：" + module[0] + "。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                        //      //}

                        //  }


                        //针对于标准件标准格式为（图号 空格 型号） 带空格 后期改为 以空格分割  零件标准格式 有可能有型号或者无
                        //if (module.Length > 1)
                        //{
                        if (materialsJoin.Count() > 0)
                        {
                            if (t.Code != null)
                            {
                                //处理年代号
                                string yearStr = "";
                                string yearsNoZs = "";
                                string no = "";
                                int length = 0;
                                string module = "";


                                StandardOutputDto standardOutputDto = _storeFunctionsAppService.GetStandardDrawingNoDispose(t.Code);
                                if (standardOutputDto.IsStandar == 0)
                                {
                                    string[] codeStr = t.Code.Split(' ');
                                    if (codeStr.Length > 1)
                                    {
                                        var materialsContentDefault = materialsJoin.FirstOrDefault(c => c.MaterialNo == standardOutputDto.ProductDrawingNo && c.Model == codeStr[1].Replace("X", "x").Replace("*", "x").Replace("×", "x"));
                                        if (materialsContentDefault != null)
                                        {
                                            //已存在物料 将物料id 更新到bop明细件id中
                                            t.MaterialsContentId = materialsContentDefault.Id;
                                            _loadPieceRepository.UpdateAsync(t);
                                        }
                                        else
                                        {
                                            //否则提示新增
                                            errorsg += "物料名称：" + t.Name + "，图号：" + standardOutputDto.ProductDrawingNo + "，" + "规格：" + codeStr[1] + " 。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                                        }
                                    }
                                    else
                                    {
                                        var materialsContentDefault = materialsJoin.FirstOrDefaultAsync(c => c.MaterialNo == standardOutputDto.ProductDrawingNo && c.Model == "-").Result;
                                        if (materialsContentDefault != null)
                                        {
                                            //已存在物料 将物料id 更新到bop明细件id中
                                            t.MaterialsContentId = materialsContentDefault.Id;
                                            _loadPieceRepository.UpdateAsync(t);
                                        }
                                        else
                                        {
                                            //否则提示新增
                                            errorsg += "物料名称：" + t.Name + "，图号：" + standardOutputDto.ProductDrawingNo + "，" + "规格：- 。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                                        }
                                    }


                                }
                                else
                                {
                                    if (standardOutputDto.Module != null)
                                    {
                                        //标准件 和零件
                                        var materialsContentDefault = materialsJoin.FirstOrDefaultAsync(c => c.MaterialNo == standardOutputDto.ProductDrawingNo && c.Model == standardOutputDto.Module.Replace("X", "x").Replace("*", "x").Replace("×", "x")).Result;
                                        if (materialsContentDefault != null)
                                        {
                                            //已存在物料 将物料id 更新到bop明细件id中
                                            t.MaterialsContentId = materialsContentDefault.Id;
                                            _loadPieceRepository.UpdateAsync(t);
                                        }
                                        else
                                        {
                                            //否则提示新增
                                            errorsg += "物料名称：" + t.Name + "，图号：" + standardOutputDto.ProductDrawingNo + "，" + "规格：" + standardOutputDto.Module + "。无对应物料信息请到物料建模创建对应物料再同步\r\n";
                                        }
                                    }
                                    else errorsg += "物料名称：" + t.Name + "装入件数据不标准，请检查数据后再同步";
                                }

                            }
                        }
                    }
                    );
                    if (errorsg != "")
                    {
                        resultMessage.Message = errorsg;
                        resultMessage.code = 1;
                        return resultMessage;
                    }
                    //}
                    #endregion
                    #region 插入制造bom表
                    BomMakeContent bomMakeContent = new BomMakeContent
                    {
                        Model = bomMakeContentDto.Model,
                        MaterialsNo = bomMakeContentDto.DrawingNo,
                        MaterilsName = "火箭",
                        SendTime = bomMakeContentDto.LotNo,
                        MaterilsTypeName = "火箭",
                        BopDescId = bomMakeContentDto.ModelId.Value,
                        LotNoId = bomMakeContentDto.LotNoId
                    };
                    var bomMakeCount = _bomMakeContentRepository.FirstOrDefault(t => t.Model == bomMakeContentDto.Model && t.SendTime == bomMakeContentDto.LotNo);
                    if (bomMakeCount == null)
                    {
                        var guid = _bomMakeContentRepository.InsertAndGetId(bomMakeContent);
                        _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.制造BOM同步, OperationTypes.新增, bomMakeContentDto.Model + bomMakeContentDto.LotNo + "制造BOM同步新增");
                        resultMessage.code = 0;
                        resultMessage.Message = "同步成功";
                        return resultMessage;
                    };
                    _iOperationHistoryAppService.InsertOperationLogNew(bomMakeCount.Id, BusinessTypes.制造BOM同步, OperationTypes.修改, bomMakeContentDto.Model + bomMakeContentDto.LotNo + "制造BOM同步更新");
                    #endregion
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该发次下没有对应装入件信息";
                    return resultMessage;
                }
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
            return resultMessage;
        }
        /// <summary>
        /// 主表格数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMakeContentDto>> GetMakeBomContent(BomMakePageEditDto input)
        {
            var queryBomMakes = from bomMakeContent in _bomMakeContentRepository.GetAll().
                         WhereIf(!input.MaterialsNo.IsNullOrWhiteSpace(), x => x.MaterialsNo.Contains(input.MaterialsNo)).WhereIf(!input.MaterilsName.IsNullOrWhiteSpace(), x => x.MaterilsName.Contains(input.MaterilsName)).WhereIf(!input.Model.IsNullOrWhiteSpace(), x => x.Model.Contains(input.Model)).WhereIf(!input.SendTime.IsNullOrWhiteSpace(), x => x.SendTime.Contains(input.SendTime))
                                from mt in _makeTaskRepository.GetAll()
                                where bomMakeContent.BopDescId == mt.ModelId && bomMakeContent.LotNoId == mt.LotNoId
                                select new BomMakeContentDto
                                {
                                    Id = bomMakeContent.Id,
                                    CreatorUserId = bomMakeContent.CreatorUserId,
                                    BopDescId = bomMakeContent.BopDescId,
                                    MaterialsNo = bomMakeContent.MaterialsNo,
                                    Model = bomMakeContent.Model,
                                    MaterilsName = bomMakeContent.MaterilsName,
                                    SendTime = bomMakeContent.SendTime,
                                    LotNoId = bomMakeContent.LotNoId,
                                    MaterilsTypeName = bomMakeContent.MaterilsTypeName,
                                    BomMakeVersion = bomMakeContent.BomMakeVersion,
                                    BomDesignId = bomMakeContent.BomDesignId,
                                    CreateUserName = bomMakeContent.CreateUserName,
                                    RocketState = mt.RocketState
                                };
            if (queryBomMakes != null)
            {
                try
                {
                    var bomMakeContentDataList = await queryBomMakes.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    //var listNew = ObjectMapper.Map<List<BomMakeContentDto>>(bomMakeContentDataList);
                    return new PagedResultDto<BomMakeContentDto>(queryBomMakes.Count(), bomMakeContentDataList);

                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            else
            {
                throw new UserFriendlyException("异常,请重试或联系管理员");
            }
        }
    }
}
